﻿# ----------------------------------------------------------- #
# Active Directory Domain Services (ADDS) Group Configuration #
# ----------------------------------------------------------- #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' executing Active Directory group '$($script.type)' configuration ... " -NoNewLine $true
$session = Get-VirtualMachineInstancePowerShellSession -Subscription $subscription -VirtualMachineName $virtualMachineName
switch ($script.type)
{
	"Create"
	{
		Invoke-Command -Session $session -ScriptBlock {
		    param([string]$name, [string]$description, [string]$scope, [string]$category, [string]$path)
            Import-Module ActiveDirectory
            if ((Get-ADGroup -Filter {Name -eq $name}) -eq $null)
            {
                New-ADGroup -Name $name -Description $description -GroupScope $scope -GroupCategory $category -Path $path
            }
		} -ArgumentList $script.name, $script.description, $script.scope, $script.category, $script.path
	}
	"Remove"
	{
		Invoke-Command -Session $session -ScriptBlock {
		    param([string]$name)
            Import-Module ActiveDirectory
            if ((Get-ADGroup -Filter {Name -eq $name}) -ne $null)
            {
                (Get-ADGroup -Filter {Name -eq $name}) | Remove-ADGroup -Confirm:$false
            }
		} -ArgumentList $script.name
	}
	"Add Member"
	{
        foreach ($member in $script.members.member)
        {
		    Invoke-Command -Session $session -ScriptBlock {
		        param([string]$name, [string]$member)
                Import-Module ActiveDirectory
                if ((Get-ADGroup -Filter {Name -eq $name} | Get-ADGroupMember | ? { $_.name -eq $member}) -eq $null)
                {
                    Get-ADGroup -Filter {Name -eq $name} | Add-ADGroupMember -Members $member
                }
		    } -ArgumentList $script.name, $member.userName
        }
	}
	"Remove Member"
	{
        foreach ($member in $script.members.member)
        {
		    Invoke-Command -Session $session -ScriptBlock {
		        param([string]$name, [string]$member)
                Import-Module ActiveDirectory
                if ((Get-ADGroup -Filter {Name -eq $name} | Get-ADGroupMember | ? { $_.name -eq $member}) -ne $null)
                {
                    Get-ADGroup -Filter {Name -eq $name} | Remove-ADGroupMember -Members $member -Confirm:$false
                }
		    } -ArgumentList $script.name, $member.userName
        }
    }
	default
	{
		throw "Active Directory group type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."